package com.fingard.dsp.bank.directbank.egbank01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.util.SmbFileUtil;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static com.fingard.text.StringHelper.trimEndFileSp;

/**
 * @Description TODO
 * @Author xtt
 **/
public class EGBANK01BatPayRec extends EGBANK01Base implements IBatPayRec {
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        return d_BatPayRec(p_req1988);
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        // 返回ATS的对象
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req1998.reqHeader);
        String beginDate = "";
        String batchNo = "";
        Connection conn = FGBiz.getLocalDbConn();
        Map<String, Object> selMap = JDBCHelper.execQuerySingle(conn, SELECTSEQ, new Object[]{p_req1998.reqHeader.reqSeqID, p_req1998.reqHeader.bankCode});
        if (selMap!=null && selMap.size() > 0) {
            beginDate = selMap.get("TRANSDATE").toString();
            batchNo =  selMap.get("BANKREQSEQID").toString();
            WriteBankLogLn("映射交易批次号为：" + batchNo);
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = "根据批次号未找交易日期";
            retAts.writeAfterDetail();
            WriteBankLogLn("根据批次号未找交易日期");
            return retAts;
        }
        try {
            String contractNo = "";
            //获取汇总信息
            EGBANK01Header bankHeader = new EGBANK01Header();
            XmlTextWriter xmlWriter = new XmlTextWriter();
            bankHeader.opName = "querySalarySummaryOp";
            bankHeader.serialNo = getQryTransID();
            bankHeader.needSigned = false;
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeStartElement("reqParam");

            //billCode为批量项目编号，billDesc代发代扣项目名称，useofCode批量用途编号
            xmlWriter.writeElementString("beginDate", beginDate);
            xmlWriter.writeElementString("endDate ", Format.Date8Format.format(new Date()));
            xmlWriter.writeElementString("transState ", "999");
            xmlWriter.writeElementString("payAccount ", p_req1998.ownAct);
            xmlWriter.writeElementString("turnPageBeginPos ", "1");
            xmlWriter.writeElementString("turnPageShowNum ", "50");
            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();//写入报文完成
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), bankHeader);//发送银行
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                //解析银行返回
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmprspcod = tmpBkReader.getFirstText("/HFBankData/opRep/retCode");
                    String tmprspmsg = tmpBkReader.getFirstText("/HFBankData/opRep/errMsg");
                    if (tmprspcod != null && tmprspcod.equals("0")) {
                       // batchNo = tmpBkReader.getFirstText("/HFBankData/opRep/opResultSet/opResult/batchNo");
                        contractNo = tmpBkReader.getFirstText("/HFBankData/opRep/opResult/contractNo ");
                        retAts.respCode = "0";
                        retAts.respInfo = tmprspmsg;
                        retAts.transState = tmpBkReader.getFirstText("/HFBankData/opRep/opResult/transState ");;
                        retAts.payInfoCode = tmprspcod;
                        retAts.reqSeqID = tmpBkReader.getFirstText("/HFBankData/opRep/opResult/batchNo");
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = tmprspmsg;
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
                retAts.respCode = "0";
                retAts.respInfo = tmpStrRet[1];
                retAts.reqSeqID = p_req1998.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = tmpStrRet[0];
                retAts.writeAfterDetail();
                return retAts;
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpStrRet[1];
                retAts.writeAfterDetail();
                return retAts;
            }
            bankHeader.opName = "querySalaryDetailResultOp";
            Integer totalNum = Integer.valueOf(p_req1998.totalNum);//总笔数
            String pageSize = getBankConfig().getValueAsString("pageSize","20");//每页查询数量
            int curPage = 1;
            while (totalNum>0) {
                //======拼接报文======
                //拼接请求报文体
                XmlTextWriter xmlWriter01 = new XmlTextWriter();
                bankHeader.serialNo = getQryTransID();
                bankHeader.needSigned = false;
                writeCommonHeader(xmlWriter01, bankHeader);
                xmlWriter01.writeStartElement("reqParam");
                xmlWriter01.writeElementString("contractNo ", this.getBankConfig().getMapValueByKey("contractNoMapping",p_req1998.ownAct));
                xmlWriter01.writeElementString("batchNo", batchNo);
                xmlWriter01.writeElementString("isSuccess","2");//0：失败；1：成功；2：全部
                xmlWriter01.writeElementString("queryFlag ","1");
                xmlWriter01.writeElementString("turnPageBeginPos", String.valueOf((curPage-1) * Integer.parseInt(pageSize) + 1));
                xmlWriter01.writeElementString("turnPageShowNum",pageSize);
                xmlWriter01.writeEndDocument();

                String[] bankResult = sendToBank(xmlWriter01.toXmlString(),bankHeader);
                if (bankResult[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String respCode = tmpBkReader.getFirstText("/HFBankData/opRep/retCode");
                        String respInfo = tmpBkReader.getFirstText("/HFBankData/opRep/errMsg");
                        if (respCode != null && respCode.equals("0")) {
                            retAts.respCode = "0";
                            retAts.respInfo = respCode + "+" + tmpBkReader.getFirstText("/HFBankData/opRep/orderState");
                            String payName = tmpBkReader.getFirstText("/ebank/body/payAccountName");
                            retAts.reqSeqID = p_req1998.reqBatchNO;
                            totalNum = StringHelper.changeStrToNum(tmpBkReader.getFirstText("/HFBankData/opRep/opResult/TTNM"));
                            while (tmpBkReader.read("/HFBankData/opRep/opResultSet/opResult")) {
                                RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                                tmpRetDetail.payAct = p_req1998.ownAct;
                                tmpRetDetail.payName = payName;
                                tmpRetDetail.recAct = tmpBkReader.readedXElement.getSingleText("REAC");//收款人号
                                tmpRetDetail.recName = tmpBkReader.readedXElement.getSingleText("ACNM");//收款人名
                                tmpRetDetail.postScript = tmpBkReader.readedXElement.getSingleText("ACTP");//批内流水号
                                tmpRetDetail.payAmount = tmpBkReader.readedXElement.getSingleText("PAMT");//金额
                                tmpRetDetail.memo =  tmpBkReader.readedXElement.getSingleText("FRES");//备注
                                tmpRetDetail.result = respCode + "+" + tmpBkReader.readedXElement.getSingleText("SFLG");
                                tmpRetDetail.payInfoCode = tmpRetDetail.result;
                                retAts.writeRetDetail(tmpRetDetail);
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = respInfo;
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpSbMsg.toString();
                    }
                    totalNum -= Integer.parseInt(pageSize);
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = bankResult[1];
                }
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
        } finally {
            conn.close();
        }
        if ("-1".equals(retAts.respCode) && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_req1998.reqBatchNO;
        }
        if ("-1".equals(retAts.respCode)) {
            retAts.writeBeforeDetail();
        }
        retAts.writeAfterDetail();
        return retAts;
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return null;
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return null;
    }

    //批量代收和批量代付提交
    public RetAtsBatPayRec d_BatPayRec(ReqBatPayRec p_reqBat) throws Exception {
        //返回ATS的对象
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
        try {
            FileOutputStream fos = null;
            String p_FileName = p_reqBat.reqHeader.reqSeqID + ".xls";
            String tmpFilePath = getTempFileDirectory() + "/uploads/" + Format.Date10Format.format(new Date());
            String p_FileFullPath = tmpFilePath + File.separator + p_FileName;
            try {
                //生成代付Excel文件
                HSSFWorkbook workbook = new HSSFWorkbook();
                HSSFSheet sheet = workbook.createSheet("Sheet1");
                HSSFRow row = sheet.createRow(0);
                row.createCell(0).setCellValue("姓名(*)");
                row.createCell(1).setCellValue("卡号/账户(*)");
                row.createCell(2).setCellValue("实发金额(*)");
                row.createCell(3).setCellValue("凭证类型(*)");

                //写入数据
                int i = 1;
                while (p_reqBat.readRecord()) {
                    String tmpCertType = "1".equals(p_reqBat.readedDetail.certType) ? "P" : "C";
                    row = sheet.createRow(i++);
                    row.createCell(0).setCellValue(p_reqBat.readedDetail.recName);
                    row.createCell(1).setCellValue(p_reqBat.readedDetail.recAct);
                    row.createCell(2).setCellValue(p_reqBat.readedDetail.payAmount);
                    row.createCell(3).setCellValue("一卡通");
                }
                if(Integer.valueOf(p_reqBat.totalNum).intValue()!=i-1){
                    WriteBankLogLn("生成批付Excel文件失败，明细和总数不一致");
                    retAts.respCode = "-1";
                    retAts.respInfo = "生成批付Excel文件失败，明细和总数不一致";
                    retAts.transState = PaymentState.FAIL_Batch;
                    retAts.payInfoCode = PaymentState.FAIL_Batch;
                    retAts.writeRetToATS();
                    return retAts;
                }

                WriteBankLogLn("批量代付生成Excel文件本地路径:" + p_FileFullPath);
                if (!FileHelper.existFile(tmpFilePath)) {
                    FileHelper.mkdir(tmpFilePath);
                }
                fos = new FileOutputStream(p_FileFullPath);
                workbook.write(fos);
                WriteBankLogLn("批量代付生成Excel文件保存成功!");
                fos.close();
            } catch (Exception e) {
                WriteBankLogLn("生成批付Excel文件失败，返回异常信息：" + e.getMessage());
                retAts.respCode = "-1";
                retAts.respInfo = "生成批付Excel文件失败，返回异常信息：" + e.getMessage();
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = PaymentState.FAIL_Batch;
                retAts.writeRetToATS();
                return retAts;
            } finally {
                if (fos != null) {
                    fos.close();
                }
            }
            /*
            //上传文件到前置机目录
            if (FileHelper.existFile(p_FileFullPath)) {
                String remotePath = trimEndFileSp(bankFront.bkTransFolder) + "/uploads/";
                int result = SmbFileUtil.smbUploading(p_FileFullPath, "", remotePath);
                if (result == -1) {
                    retAts.respCode = "-1";
                    retAts.respInfo = "上传文件到前置机目录异常";
                    retAts.writeRetToATS();
                    return retAts;
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "批付Excel文件不存在";
                retAts.writeRetToATS();
                return retAts;
            }
          */
            // #end
            EGBANK01Header bankHeader = new EGBANK01Header();
            bankHeader.opName = "uploadFileSalary";
            bankHeader.serialNo = getQryTransID();
            bankHeader.needSigned = false;

            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入通用的头部节点
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeStartElement("reqParam");

            //billCode为批量项目编号，billDesc代发代扣项目名称，useofCode批量用途编号
            xmlWriter.writeElementString("uploadFile", p_FileName);
            xmlWriter.writeElementString("payAccount ", p_reqBat.ownAct);
            xmlWriter.writeElementString("totalAmount ", p_reqBat.totalAmt);
            xmlWriter.writeElementString("totalNumber ", p_reqBat.totalNum);
     //       xmlWriter.writeElementString("sessionID ", getSessionID(bankHeader));
            xmlWriter.writeEndElement();

            xmlWriter.writeEndDocument();//写入报文完成
            String[] tmpStrRet = uploadFileToBank(xmlWriter.toXmlString(),p_FileFullPath, bankHeader,p_reqBat);//发送银行

            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                //解析银行返回
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmprspcod = tmpBkReader.getFirstText("/HFBankData/opRep/retCode");
                    String tmprspmsg = tmpBkReader.getFirstText("/HFBankData/opRep/errMsg");
                    if (tmprspcod != null && tmprspcod.equals("0")) {
                        retAts.respCode = "0";
                        retAts.respInfo = tmprspmsg;
                        retAts.transState = p_reqBat.reqHeader.commandCode  + "+" + tmprspcod;
                        retAts.payInfoCode = tmprspcod;
                        retAts.reqSeqID = tmpBkReader.getFirstText("/HFBankData/opRep/opResult/batchNo");
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = tmprspmsg;
                        retAts.writeRetToATS();
                        return retAts;
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
                retAts.respCode = "0";
                retAts.respInfo = tmpStrRet[1];
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = tmpStrRet[0];
                retAts.writeRetToATS();
                return retAts;
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpStrRet[1];
                retAts.writeRetToATS();
                return retAts;
            }
            WriteBankLogLn("开始执行代发通知。。。");
            //通知代发工资
            EGBANK01Header bankHeader01 = new EGBANK01Header();
            bankHeader01.opName = "submitGZBatchOp";
            bankHeader01.serialNo = getQryTransID();
            bankHeader01.needSigned = true;
            bankHeader01.signStrList = new String[]{"serialNo", "cstNo", "reqTime","contractNo", "batchNo", "totalAmount", "totalNumber", "payAccount"};

            XmlTextWriter xmlWriter01 = new XmlTextWriter();//发银行报文的XML对象
            //写入通用的头部节点
            writeCommonHeader(xmlWriter01, bankHeader01);
            xmlWriter01.writeStartElement("reqParam");

            //billCode为批量项目编号，billDesc代发代扣项目名称，useofCode批量用途编号
            xmlWriter01.writeElementString("contractNo ",this.getBankConfig().getMapValueByKey("contractNoMapping",p_reqBat.ownAct));
            xmlWriter01.writeElementString("batchNo  ", retAts.reqSeqID);
            xmlWriter01.writeElementString("totalAmount ", p_reqBat.totalAmt);
            xmlWriter01.writeElementString("totalNumber ", p_reqBat.totalNum);
            xmlWriter01.writeElementString("payAccount  ", p_reqBat.ownAct);

            xmlWriter01.writeEndElement();

            xmlWriter01.writeEndDocument();//写入报文完成
            String[] tmpStrRet01 = sendToBank(xmlWriter01.toXmlString(), bankHeader01);//发送银行
            if (tmpStrRet01[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                //解析银行返回
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet01[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmprspcod = tmpBkReader.getFirstText("/HFBankData/opRep/retCode");
                    String tmprspmsg = tmpBkReader.getFirstText("/HFBankData/opRep/errMsg");
                    if (tmprspcod != null && tmprspcod.equals("0")) {
                        retAts.respCode = "0";
                        retAts.respInfo = tmprspmsg;
                        retAts.transState = p_reqBat.reqHeader.commandCode + "+" + tmpBkReader.getFirstText("/HFBankData/opRep/opResult/orderState");
                        retAts.payInfoCode = tmprspcod;
                        retAts.reqSeqID = tmpBkReader.getFirstText("/HFBankData/opRep/opResult/batchNo");
                    } else {
                        retAts.respCode = "0";
                        retAts.transState = p_reqBat.reqHeader.commandCode + "+" + tmprspcod;
                        retAts.payInfoCode = tmprspcod;
                        retAts.reqSeqID = tmpBkReader.getFirstText("/HFBankData/opRep/opResult/batchNo");
                        retAts.respInfo = tmprspmsg;
                    }
                    Connection conn = FGBiz.getLocalDbConn();
                    String uuids = UUID.randomUUID().toString().replaceAll("-", "");
                    JDBCHelper.update(conn, INSERTSEQ, new Object[]{uuids, p_reqBat.reqHeader.bankCode, Format.Date8Format.format(new Date()), p_reqBat.reqHeader.reqSeqID,retAts.reqSeqID});
                    WriteBankLogLn("已完成映射日期和批次号存入：" + p_reqBat.reqHeader.reqSeqID + "日期为：" + Format.Date8Format.format(new Date()));
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
                retAts.respCode = "0";
                retAts.respInfo = tmpStrRet[1];
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = tmpStrRet[0];
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpStrRet[1];
            }

        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.toString();
            e.printStackTrace();
        }
        if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_reqBat.reqBatchNO;
        }
        retAts.writeRetToATS();
        return retAts;
    }

    public boolean generateBatchXlsFile(String templateFilePath, String generateFilePath, String generateFileName, ReqBatPayRec p_req1988) throws Exception {
        boolean flag = false;
        try {
            if (templateFilePath.length() > 0 && FileHelper.existFile(templateFilePath)) {
                //1.poi读取批量转账模版文件
                FileInputStream fis = new FileInputStream(templateFilePath);
                HSSFWorkbook workbook = new HSSFWorkbook(fis);
                //得到第一页 sheet
                //页Sheet是从0开始索引的
                HSSFSheet hssfSheet = workbook.getSheetAt(0);
                //2.根据请求报文填充文件
                int currentNum = 0;
                while (p_req1988.readRecord()) {
                    HSSFRow hssfRow = hssfSheet.createRow(currentNum + 1);
                    String purpose = "";
                    //第一列为姓名
                    hssfRow.createCell(0).setCellValue(p_req1988.readedDetail.recName);
                    //第二列账号
                    hssfRow.createCell(1).setCellValue(p_req1988.readedDetail.recAct);
                    //第三列金額
                    hssfRow.createCell(2).setCellValue(p_req1988.readedDetail.payAmount);
                    //第四列为收款单位账号
                    hssfRow.createCell(3).setCellValue("一卡通");
                    currentNum++;
                }
                //3.另存文件到指定目录
                String fileFullPath = generateFilePath + generateFileName;
                OutputStream outputStream = new FileOutputStream(fileFullPath);
                workbook.write(outputStream);
                outputStream.close();
                flag =true;
                WriteBankLogLn2("生成批量转账文件成功");
            } else {
                flag = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    /*
    private String uploadFileToBank(String p_filePath, StringBuilder p_sb) throws Exception {
        CCB02Header bankHeader = new CCB02Header();
        bankHeader.REQUEST_SN = this.getQryTransID();
        bankHeader.TX_CODE = "6W2102";
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        xmlWriter.autoFormat = false;
        writeCommonHeader(xmlWriter, bankHeader);
        xmlWriter.writeStartElement("TX_INFO");
        xmlWriter.writeElementString("SEND_FILE", p_filePath);
        xmlWriter.writeEndDocument();
        String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());//发送银行
        if (tmpStrRet[0].length() == 0) {
            //解析银行返回
            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], p_sb);
            if (tmpBkReader != null) {
                String RETURN_CODE = tmpBkReader.getFirstText("/TX/RETURN_CODE");
                String RETURN_MSG = tmpBkReader.getFirstText("/TX/RETURN_MSG");
                if (RETURN_CODE.equals("000000")) {
                    String SEND_FILE = tmpBkReader.getFirstText("/TX/TX_INFO/SEND_FILE");
                    if (StringHelper.hasAnyChar(SEND_FILE)) {
                        return SEND_FILE;
                    }
                } else {
                    p_sb.append(RETURN_MSG);
                }
            }
        } else {
            p_sb.append(tmpStrRet[1]);
        }
        return "";
    }*/
}
